package com.nsoft.thickclient.trackMove.user;

import java.awt.BorderLayout;
import java.awt.FlowLayout;

import javax.swing.Box;
import javax.swing.JPanel;

import com.nsoft.server.service.main.UserService;
import com.nsoft.server.serviceImpl.FacadeFactoryImpl;
import com.nsoft.thickclient.beanUtils.ActionDescriptor;
import com.nsoft.thickclient.beanUtils.NButton;
import com.nsoft.thickclient.controller.ScreenController;
import com.nsoft.thickclient.trackMove.intr.user.User;

public class LoginViewController extends ScreenController {

	private JPanel mainPanel;

	private ActionDescriptor saveAction = new ActionDescriptor("Save",
			"doSave", this);

	private ActionDescriptor newAction = new ActionDescriptor("New", "doNew",
			this);

	private ActionDescriptor cancelAction = new ActionDescriptor("Cancel",
			"doCancel", this);

	private UserView userView;

	private boolean editMode;

	public boolean isEditinMode() {
		return editMode;
	}

	public void setEditinMode(boolean editinMode) {
		this.editMode = editinMode;
	}

	public LoginViewController() {
		editMode = false;
	}

	public LoginViewController(boolean editinMode) {
		this.editMode = editinMode;
	}

	@Override
	public void close() {
		// TODO Auto-generated method stub

	}

	@Override
	public String getScreenTitle() {
		return "Manage user";
	}

	@Override
	public JPanel getView() {
		return mainPanel;
	}

	@Override
	public void init() {
		mainPanel = new JPanel(new BorderLayout());
		userView = new UserView(false);
		mainPanel.add(userView, BorderLayout.PAGE_START);
		mainPanel.add(getButtonPanel(), BorderLayout.PAGE_END);

	}

	private JPanel getButtonPanel() {
		JPanel butonPanel = new JPanel(new FlowLayout(FlowLayout.CENTER));
		butonPanel.add(new NButton(saveAction));
		butonPanel.add(Box.createHorizontalStrut(20));
		butonPanel.add(new NButton(newAction, !editMode));
		butonPanel.add(Box.createHorizontalStrut(20));
		butonPanel.add(new NButton(cancelAction));
		return butonPanel;
	}

	public void doSave() {
		
		UserService service = FacadeFactoryImpl.getUserService();
		User user =service.saveUser((User)userView.getModel().getValueObject());
		if (!editMode) {
			doNew();
			userView.setWorkingBean(user);
		} else {
			
			doCancel();
		}
	}

	public void doNew() {
		userView.getModel().setValueObject(new User());
	}

	public void doCancel() {
		getApplicationController().closeScreen(this);
	}

	public UserView getUserView() {
		return userView;
	}

	public void setUserView(UserView userView) {
		this.userView = userView;
	}
}
